package com.andnnl.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.LongAdder;

/**
 * Created by chenss on 2021/6/23.
 */
public class UserQueue<T> {
    private static final Logger logger = LoggerFactory.getLogger(UserQueue.class);
    private final BlockingQueue<IUser<T>> queue = new LinkedBlockingQueue<>();
    //    private BlockingQueue<User> queue = new ArrayBlockingQueue(200000);//最多20W用户
    private final LongAdder ignoreCount = new LongAdder();//忽略计数
    private final LongAdder addCount = new LongAdder();//添加计数
    private boolean isTest = false;//测试模式，才计数

    public void addUser(IUser<T> user) {
        user.resetCurrTime();//每操作一次都要更新最新时间
        //如果不在队列，就添加到队列后再处理,（不用synchronized同步）
        if (user.getInQueue().compareAndSet(false, true)) {
            //多线程情况下，如果已经进入这里，而且在TaskManage中被改为false，会重新进入
            // ，但又因为TaskManage中已经被task出来，所以queue里还是没有相同的user
            queue.add(user);
            if (isTest) addCount.increment();
        } else {
            if (isTest) ignoreCount.increment();
        }
    }

    public IUser<T> taskUser() {
        try {
            return queue.take();
        } catch (Exception e) {
            logger.error("catch Exception taskUser error " + e.getMessage(), e);
        }
        return null;
    }

    public LongAdder getIgnoreCount() {
        return ignoreCount;
    }

    public LongAdder getAddCount() {
        return addCount;
    }

    public void setTest(boolean test) {
        isTest = test;
    }

    public int getQueueSize() {
        return queue.size();
    }
}
